import { selectors } from "./config.js";
import { AlertHelper } from "../../utils/alert-helper.js";

export class DateManager {
  constructor() {
    this._lastSetRange = null;
    this._periodType = null;
    this._observer = null;
    this._isObserving = false;
    this._isSettingDates = false;
    this._lastTriggerTime = 0;
    this._debounceTime = 1000; // 1秒的防抖时间
  }

  // 初始化观察器
  initObserver() {
    if (typeof MutationObserver === "undefined") {
      console.warn(
        "MutationObserver not available, date picker detection may not work properly"
      );
      return;
    }

    // 如果已经有观察器在运行，先停止它
    if (this._observer) {
      this._observer.disconnect();
      this._isObserving = false;
    }

    // 创建新的观察器
    this._observer = new MutationObserver((mutations) => {
      // 防抖处理
      const now = Date.now();
      if (now - this._lastTriggerTime < this._debounceTime) {
        return;
      }
      this._lastTriggerTime = now;

      // 如果正在设置日期，不处理新的变化
      if (this._isSettingDates) {
        return;
      }

      for (const mutation of mutations) {
        if (mutation.addedNodes && mutation.addedNodes.length > 0) {
          for (const node of mutation.addedNodes) {
            if (
              node.nodeType === 1 &&
              node.classList &&
              node.classList.contains(selectors.datePickerPopup.slice(1))
            ) {
              console.log("日期选择器弹出");
              this.autoSetDateRangeIfNeeded();
              break; // 找到后立即退出循环
            }
          }
        }
      }
    });

    // 开始观察
    this._observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
    this._isObserving = true;
  }

  // 设置自定义日期范围
  async setCustomDateRange(startDate, endDate) {
    if (this._isSettingDates) {
      console.log("正在设置日期，跳过重复操作");
      return;
    }

    this._isSettingDates = true;
    try {
      const key = `${startDate}|${endDate}`;
      if (this._lastSetRange === key) {
        console.log("日期范围未变化，跳过设置");
        AlertHelper.warning("日期范围未变化，跳过设置");
        // return; // TODO: 暂时不跳过，因为需要重新设置日期范围，将来可以增加对页面的判断。
      }
      this._lastSetRange = key;

      // 保存周期类型
      if (window._customDateRange && window._customDateRange.periodType) {
        this._periodType = window._customDateRange.periodType;
      }

      // 第1步：通过日期范围判断是否为近七日
      const isLast7Days = this.isLast7DaysRange(startDate, endDate);
      console.log("是否为近七日范围:", isLast7Days);

      if (isLast7Days) {
        // 近七日：直接点击近7天选项
        console.log("处理近7天选项");
        await this.handleLast7DaysOption();
      } else {
        // 自定义：触发鼠标悬浮自定义节点
        console.log("处理自定义日期选项");
        await this.handleCustomDateOption(startDate, endDate);
      }
    } finally {
      this._isSettingDates = false;
    }
  }

  // 判断是否为近七日范围
  isLast7DaysRange(startDate, endDate) {
    try {
      const start = new Date(startDate);
      const end = new Date(endDate);
      const today = new Date();

      // 计算日期差（毫秒转换为天数）
      const diffTime = Math.abs(end - start);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      // 检查是否为7天范围
      const is7DaysRange = diffDays === 6; // 7天范围是6天的差值

      // 检查结束日期是否为昨天（因为我们之前修改了日期计算，不包含今天）
      const yesterday = new Date(today);
      yesterday.setDate(today.getDate() - 1);
      const isEndDateYesterday =
        end.toDateString() === yesterday.toDateString();

      console.log("日期分析:", {
        startDate: start.toDateString(),
        endDate: end.toDateString(),
        diffDays,
        is7DaysRange,
        isEndDateYesterday,
        yesterday: yesterday.toDateString(),
      });

      return is7DaysRange && isEndDateYesterday;
    } catch (error) {
      console.error("日期解析错误:", error);
      return false;
    }
  }

  // 处理近7天选项
  async handleLast7DaysOption() {
    console.log("处理近7天选项");

    // 直接查找并点击近7天选项，无需触发弹出框
    const last7DaysOption = this.findLast7DaysOption();

    if (last7DaysOption) {
      last7DaysOption.click();
      console.log("已直接点击近7天选项");
      AlertHelper.success("已选择近7天");
      return true;
    } else {
      console.log("未找到近7天选项，尝试触发日期选择器");
      AlertHelper.warning("未找到近7天选项，尝试触发日期选择器");
      // 如果找不到直接的选项，则触发日期选择器
      return await this.fallbackToDatePicker();
    }
  }

  // 查找近7天选项
  findLast7DaysOption() {
    // 查找包含"近7天"或"近七天"文本的标签
    const last7DaysOption =
      this.findElementByText("近7天") ||
      this.findElementByText("近七天") ||
      this.findElementByText("近7日") ||
      this.findElementByText("近七日");

    if (last7DaysOption) {
      console.log("找到近7天选项:", last7DaysOption);
      return last7DaysOption;
    }

    // 如果没找到，尝试在日期选择器弹出框中查找
    const popup = document.querySelector(selectors.datePickerPopup);
    if (popup) {
      const optionInPopup =
        popup.querySelector(".byted-tag") &&
        (popup.querySelector(".byted-tag").textContent.includes("近7天") ||
          popup.querySelector(".byted-tag").textContent.includes("近七天") ||
          popup.querySelector(".byted-tag").textContent.includes("近7日") ||
          popup.querySelector(".byted-tag").textContent.includes("近七日"));
      if (optionInPopup) {
        console.log("在弹出框中找到近7天选项");
        return optionInPopup;
      }
    }

    return null;
  }

  // 回退到日期选择器触发
  async fallbackToDatePicker() {
    const hasDatePicker = await this.triggerDatePickerPopup();
    if (!hasDatePicker) {
      console.log("当前页面没有日期选择器，跳过日期设置");
      AlertHelper.error("当前页面没有日期选择器，跳过日期设置");
      return false;
    }

    // 显示提示框
    AlertHelper.warning("已识别到日期选择器，准备选择近7天");

    // 等待日期选择器弹出
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 选择近7天选项
    return await this.selectLast7DaysOption();
  }

  // 处理自定义日期选项
  async handleCustomDateOption(startDate, endDate) {
    console.log("处理自定义日期选项");

    // 1. 查找自定义选项并触发鼠标悬浮
    const customOption = this.findCustomOption();

    if (customOption) {
      // 触发自定义节点的鼠标悬浮
      await this.triggerCustomOptionHover(customOption);

      // 显示提示框
      AlertHelper.warning("已触发自定义选项，准备设置日期范围");

      // 等待自定义选项生效
      await new Promise((resolve) => setTimeout(resolve, 500));

      // 使用setDateRangeInPicker方法进行时间选择
      await this.setDateRangeInPicker(startDate, endDate);
    } else {
      console.log("未找到自定义选项，尝试触发日期选择器");
      // 如果找不到自定义选项，则回退到传统方法
      await this.fallbackToCustomDatePicker(startDate, endDate);
    }
  }

  // 查找自定义选项
  findCustomOption() {
    // 查找包含"自定义"文本的标签
    const customOption = this.findElementByText("自定义");

    if (customOption) {
      console.log("找到自定义选项:", customOption);
      return customOption;
    }

    // 如果没找到，尝试在日期选择器弹出框中查找
    const popup = document.querySelector(selectors.datePickerPopup);
    if (popup) {
      const optionInPopup =
        popup.querySelector(".byted-tag") &&
        popup.querySelector(".byted-tag").textContent.includes("自定义");
      if (optionInPopup) {
        console.log("在弹出框中找到自定义选项");
        return optionInPopup;
      }
    }

    return null;
  }

  // 触发自定义选项的鼠标悬浮
  async triggerCustomOptionHover(customOption) {
    console.log("触发自定义选项的鼠标悬浮");

    // 创建鼠标悬浮事件
    const mouseoverEvent = new MouseEvent("mouseover", {
      view: window,
      bubbles: true,
      cancelable: true,
    });

    // 触发鼠标悬浮
    customOption.dispatchEvent(mouseoverEvent);

    // 等待一小段时间后点击
    await new Promise((resolve) => setTimeout(resolve, 100));
    customOption.click();

    console.log("已触发自定义选项的鼠标悬浮并点击");
  }

  // 回退到传统日期选择器方法
  async fallbackToCustomDatePicker(startDate, endDate) {
    // 使用mouseover触发时间选择器弹出
    const hasDatePicker = await this.triggerDatePickerPopup();
    if (!hasDatePicker) {
      console.log("当前页面没有日期选择器，跳过日期设置");
      return;
    }

    // 显示提示框
    AlertHelper.warning("已识别到日期选择器，准备设置自定义日期范围");

    // 等待日期选择器弹出
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 选择自定义选项
    await this.selectCustomOption();

    // 等待自定义选项生效
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 使用setDateRangeInPicker方法进行时间选择
    await this.setDateRangeInPicker(startDate, endDate);
  }

  // 触发日期选择器弹出
  async triggerDatePickerPopup() {
    // 查找日期选择器触发元素（通常是输入框或按钮）
    const datePickerTrigger =
      document.querySelector("#realtime-data-picker") ||
      document.querySelector('[data-tracker-id*="picker"]') ||
      document.querySelector(".byted-date-picker-trigger");

    if (!datePickerTrigger) {
      console.log("未找到日期选择器触发元素");
      AlertHelper.error("未找到日期选择器触发元素");
      return false;
    }

    console.log(
      "🚀 ~ DateManager ~ triggerDatePickerPopup ~ datePickerTrigger:",
      datePickerTrigger
    );

    // 使用mouseover事件触发弹出
    const mouseoverEvent = new MouseEvent("mouseover", {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    datePickerTrigger.dispatchEvent(mouseoverEvent);

    // 如果mouseover不生效，尝试click
    setTimeout(() => {
      if (!document.querySelector(selectors.datePickerPopup)) {
        console.log("mouseover未触发弹出，尝试click");
        datePickerTrigger.click();
      }
    }, 100);

    return true;
  }

  // 选择近7天选项
  async selectLast7DaysOption() {
    console.log("选择近7天选项");

    // 查找包含"近7天"或"近七天"文本的标签
    const last7DaysOption =
      this.findElementByText("近7天") || this.findElementByText("近七天");

    if (last7DaysOption) {
      last7DaysOption.click();
      console.log("已点击近7天选项");
      return true;
    } else {
      console.error("未找到近7天选项");
      return false;
    }
  }

  // 选择自定义选项
  async selectCustomOption() {
    console.log("选择自定义选项");

    // 查找包含"自定义"文本的标签
    const customOption = this.findElementByText("自定义");

    if (customOption) {
      customOption.click();
      console.log("已点击自定义选项");
      return true;
    } else {
      console.error("未找到自定义选项");
      return false;
    }
  }

  // 根据文本内容查找元素
  findElementByText(text) {
    const elements = document.querySelectorAll(selectors.dateOptionTag);
    for (const element of elements) {
      if (element.textContent.includes(text)) {
        return element;
      }
    }
    return null;
  }

  // 获取当前周期类型
  getPeriodType() {
    return this._periodType;
  }

  // 辅助函数：获取面板的年和月
  getPanelYearMonth(panel) {
    const yearSpan = panel.querySelector('.byted-date-title-item:nth-child(1)');
    const monthSpan = panel.querySelector('.byted-date-title-item:nth-child(2)');
    if (!yearSpan || !monthSpan) return null;
    const year = parseInt(yearSpan.textContent.replace('年', ''), 10);
    const month = parseInt(monthSpan.textContent.replace('月', ''), 10);
    return { year, month };
  }

  // 辅助函数：在指定面板下查找日期节点
  findDateItem(panel, day) {
    const items = panel.querySelectorAll('.byted-date-item:not(.byted-date-disabled)');
    for (const item of items) {
      if (item.textContent.trim() === String(day)) {
        return item;
      }
    }
    return null;
  }

  // 辅助函数：切换到目标年月（type: 'start' | 'end'）
  async switchToYearMonth(targetYear, targetMonth) {
    let maxTry = 24; // 最多切换24次，防止死循环
    while (maxTry-- > 0) {
      // 获取所有面板的年月
      const panels = Array.from(document.querySelectorAll('.byted-date-view'));
      const ymList = panels.map(p => this.getPanelYearMonth(p)).filter(Boolean);

      // 检查目标年月是否已在面板中
      if (ymList.some(ym => ym.year === targetYear && ym.month === targetMonth)) return;

      // 找到最小和最大年月
      const min = ymList.reduce((a, b) => (a.year < b.year || (a.year === b.year && a.month < b.month)) ? a : b);
      const max = ymList.reduce((a, b) => (a.year > b.year || (a.year === b.year && a.month > b.month)) ? a : b);

      // 目标在左边还是右边
      if (targetYear < min.year || (targetYear === min.year && targetMonth < min.month)) {
        // 点左箭头（任意一个面板的左箭头都可以）
        const leftBtn = panels[0].querySelector('.byted-date-nav-prev .byted-icon');
        if (leftBtn) leftBtn.click();
      } else if (targetYear > max.year || (targetYear === max.year && targetMonth > max.month)) {
        // 点右箭头
        const rightBtn = panels[panels.length - 1].querySelector('.byted-date-nav-next .byted-icon');
        if (rightBtn) rightBtn.click();
      } else {
        // 理论不会到这里
        break;
      }
      await new Promise(r => setTimeout(r, 250)); // 等待动画和渲染
    }
    throw new Error('切换年月失败，超过最大尝试次数');
  }

  // 在日期选择器中设置日期范围（集成年月面板校验+箭头切换）
  async setDateRangeInPicker(startDateStr, endDateStr) {
    console.log(
      "🚀 ~ DateManager ~ setDateRangeInPicker ~ setDateRangeInPicker:",
      startDateStr,
      endDateStr
    );
    const [startYear, startMonth, startDay] = startDateStr.split("-").map(Number);
    const [endYear, endMonth, endDay] = endDateStr.split("-").map(Number);

    // 切换到目标年月
    await this.switchToYearMonth(startYear, startMonth);
    await this.switchToYearMonth(endYear, endMonth);

    // 获取所有面板
    const panels = document.querySelectorAll('.byted-date-view');
    let startPanel = null, endPanel = null;
    for (const panel of panels) {
      const ym = this.getPanelYearMonth(panel);
      if (!ym) continue;
      if (ym.year === startYear && ym.month === startMonth) startPanel = panel;
      if (ym.year === endYear && ym.month === endMonth) endPanel = panel;
    }
    if (!startPanel) throw new Error(`未找到${startYear}年${startMonth}月的面板`);
    const startItem = this.findDateItem(startPanel, startDay);
    if (!startItem) throw new Error(`未找到开始日期${startDay}`);
    startItem.click();
    if (!endPanel) throw new Error(`未找到${endYear}年${endMonth}月的面板`);
    const endItem = this.findDateItem(endPanel, endDay);
    if (!endItem) throw new Error(`未找到结束日期${endDay}`);
    endItem.click();
    AlertHelper.success("已设置日期范围");
    return true;
  }

  // 自动设置日期范围（如果需要）
  autoSetDateRangeIfNeeded() {
    if (!window._customDateRange) return;
    this.setCustomDateRange(
      window._customDateRange.startDate,
      window._customDateRange.endDate
    );
  }
}
